<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice</title>
    <style>
        .image-container {
            position: relative;
            display: inline-block;
        }

        #avatar {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            margin-bottom: 20px;
            object-fit: cover;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
            display: block;
        }

        .hover-text {
            position: absolute;
            top: 80%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(228, 228, 228, 0.7);
            color: #8c8b8b;
            padding: 5px 10px;
            border-radius: 5px;
            opacity: 0;
            transition: opacity 0.3s;
            font-size: 14px;
            width: 60px;
            text-align: center;
        }

        .image-container:hover .hover-text {
            opacity: 1;
        }

        #fileInput {
            display: none;
        }
    </style>
</head>
<body>
<div class="image-container">
    <img id="avatar" src="/icon/个人.png" alt="用户头像">
    <div class="hover-text">修改头像</div>
    <input type="file" id="fileInput" accept="image/*">
</div>

</body>
<script >
    const avatar = document.getElementById('avatar');
    const fileInput = document.getElementById('fileInput');

    avatar.addEventListener('click', () => {
        fileInput.click();
    });

    fileInput.addEventListener('change', () => {
        const file = fileInput.files[0];
        if (file) {
            const formData = new FormData();
            formData.append('image', file);

            const userId = localStorage.getItem('userId');  // 获取用户ID可以不需要，删除即可
            if (userId) {
                formData.append('userId', userId);
            }

            fetch('http://localhost:8080/upload', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 1) {
                        avatar.src = data.data; // 更新图片URL
                        localStorage.setItem('avatar', data.data); // 保存头像URL到 localStorage
                    } else {
                        alert('上传失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('上传出错');
                });
        }
    });

</script>
</html>
